﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Text;
using System.IO;
using System.Drawing.Imaging;

namespace HPortal.Lib
{
    public class HtmlHelper
    {
        public static void Script(string Script, System.Web.UI.Page Page)
        {
            if (Script != null)
                Page.RegisterStartupScript("Script", "<script>" + Script + "</script>");
        }

        public static void Alert(string Message, System.Web.UI.Page Page)
        {
            if (Message != null)
                Page.RegisterStartupScript("AlertScript", "<script>alert(" + EscapeQuote(Message) + ")</script>");
        }

        public static void Confirm(string Message, string ifTrue, string ifFalse, System.Web.UI.Page Page)
        {
            if (Message != null)
                Page.RegisterStartupScript("ConfirmScript", string.Format("<script>\r\nif (window.confirm({0}))\r\n{{{1}}}\r\nelse\r\n{{{2}}}\r\n</script>", EscapeQuote(Message), ifTrue, ifFalse));
        }

        public static void Back(int Step, System.Web.UI.Page Page)
        {
            Page.RegisterStartupScript("BackScript", "<script>history.go(" + Step + ")</script>");
        }

        public static void Navigate(string Href, System.Web.UI.Page Page)
        {
            Page.RegisterStartupScript("NavigateScript", "<script>location.href='" + Href + "'</script>");
        }

        public static bool IsEmptyTextBox(System.Web.UI.WebControls.TextBox textBox)
        {
            return textBox.Text.Trim().Length == 0;
        }

        public static int TryParse(string s, int def)
        {
            try
            {
                return int.Parse(s);
            }
            catch
            {
                return def;
            }
        }

        public static DateTime TryParse(string s, DateTime def)
        {
            try
            {
                return DateTime.Parse(s);
            }
            catch
            {
                return def;
            }
        }

        public static string FormatDateTime(DateTime d)
        {
            return d.ToString("dd/MM/yyyy");
        }

        public static string JoinTwoStrings(string s1, string s2, string separator)
        {
            if (s1 == null)
                return s2;
            if (s2 == null)
                return s1;
            return s1 + separator + s2;
        }

        public static string EscapeQuote(string S)
        {
            if (S == null)
                return "''";
            //			else
            //				return "'" + S.Trim().Replace("'", "\\'").Replace("\r\n", "\\r\\n") + "'";
            StringBuilder sb = new StringBuilder("'", S.Length + 2);
            foreach (char c in S)
            {
                if (c == '\'')
                    sb.Append("\\'");
                else if (c == '\r')
                    sb.Append("\\r");
                else if (c == '\n')
                    sb.Append("\\n");
                else if (c > '~')
                    sb.Append("&#" + Convert.ToInt16(c) + ";");
                else
                    sb.Append(c);
            }
            sb.Append("'");
            return sb.ToString();
        }

        public static string StripHtml(string S)
        {
            int i = 0, j = 0;
            while (((i = S.IndexOf("<", i)) != -1) && ((j = S.IndexOf(">", i)) != -1))
                S = S.Remove(i, j - i + 1);

            return S.Trim();
        }

        public static string StripParagraph(string S)
        {
            int i = S.IndexOf(">");
            if (i != -1)
                return S.Substring(i + 1).Trim();
            else
                return S.Trim();
        }

        public static string NormalizeHtml(string S)
        {
            int i = 0, j = 0;
            while (((i = S.IndexOf("/ImageView.aspx?", j)) != -1) && ((j = S.LastIndexOf('\"', i)) != -1))
                S = S.Remove(j + 1, i - j);

            return S.Replace("<P>", "<P class=pBody>");
        }

        public static int GetImageID(string strEditor)
        {
            try
            {
                string StrCompe = "img.aspx?ImageID=";
                int intStr = strEditor.IndexOf(StrCompe, 0);
                if (intStr == -1)
                    return 0;
                else
                {
                    int n = 0;
                    intStr = intStr + StrCompe.Length;
                    char s = strEditor[intStr + n];
                    while (s >= 48 && s <= 57)
                    {
                        n++;
                        s = strEditor[intStr + n];
                    }
                    if (n == 0)
                        return 0;
                    else
                        return int.Parse(strEditor.Substring(intStr, n));
                }
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static string GetContentOfClass(string strEditor, string strClass)
        {
            try
            {
                string strTab = string.Empty;
                //class
                string StrCompe = "class=\"" + strClass + "\"";
                int intStr = strEditor.IndexOf(StrCompe);
                if (intStr != -1)
                // find tag
                {
                    intStr = strEditor.LastIndexOf("<", intStr);
                    if (intStr != -1)
                    {
                        intStr++;
                        int n = 0;
                        char s = strEditor[intStr + n];
                        while (s != 32)
                        {
                            n++;
                            s = strEditor[intStr + n];
                        }
                        if (n != 0)
                        {
                            strTab = strEditor.Substring(intStr, n).Trim();
                            StrCompe = ">";
                            int intBe = strEditor.IndexOf(StrCompe, intStr + n);
                            if (intBe != -1)
                            {
                                intBe++;
                                StrCompe = "</" + strTab;
                                int intEn = strEditor.IndexOf(StrCompe, intBe);
                                if (intEn != -1)
                                {
                                    string StrContent = strEditor.Substring(intBe, intEn - intBe);
                                    StrCompe = "<" + strTab;
                                    intStr = StrContent.IndexOf(StrCompe, 0);
                                    if (intStr != -1)
                                    {
                                        StrCompe = "</" + strTab;
                                        intEn = strEditor.IndexOf(StrCompe, intEn + StrCompe.Length);
                                        if (intEn != -1)
                                            StrContent = strEditor.Substring(intBe, intEn - intBe + 1);

                                    }
                                    return StrContent;
                                }
                            }
                        }
                    }
                }
                return string.Empty;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public static int ParseHtmlInt(string Source, string Prefix, string Surfix, int Start, int Default)
        {
            int i = Source.IndexOf(Prefix, Start);
            if (i != -1)
            {
                i += Prefix.Length;
                int j = Source.IndexOf(Surfix, i);
                if (j != -1)
                    try
                    {
                        return int.Parse(Source.Substring(i, j - i));
                    }
                    catch { }
            }

            return Default;
        }

        public static byte[] GetWatermark(Image Img, string Copyright, int Transparent)
        {
            int width = Img.Width;
            int height = Img.Height;

            MemoryStream ms = new MemoryStream();
            Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            Graphics grp = Graphics.FromImage(bmp);

            grp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            grp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            grp.DrawImage(Img, -1, -1, width + 2, height + 2);
            //grp.DrawImage(Img, 0, 0, Width, Height);

            Font crFont = null;
            SizeF crSize = new SizeF();
            for (int i = 100; i > 1; i--)
            {
                crFont = new Font("Arial", i, FontStyle.Bold);
                crSize = grp.MeasureString(Copyright, crFont);

                if ((ushort)crSize.Width < (ushort)width)
                    break;
            }
            float yCenterOfImg = height / 2;
            float xCenterOfImg = width / 2;

            StringFormat StrFormat = new StringFormat();
            StrFormat.Alignment = StringAlignment.Center;
            StrFormat.LineAlignment = StringAlignment.Center;
            SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(Transparent, 0, 0, 0));
            grp.DrawString(Copyright, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yCenterOfImg + 1), StrFormat);
            SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(Transparent, 255, 255, 255));
            grp.DrawString(Copyright, crFont, semiTransBrush, new PointF(xCenterOfImg, yCenterOfImg), StrFormat);

            bmp.Save(ms, ImageFormat.Jpeg);
            byte[] result = ms.ToArray();
            ms.Close();

            return result;
        }
        public static int GetIntFromRequestString(string RequestString, int DefaultID)
        {
            RequestString = System.Web.HttpContext.Current.Request.QueryString[RequestString];
            if (RequestString != null && RequestString != string.Empty)
                try
                {
                    return int.Parse(RequestString);
                }
                catch { }

            return DefaultID;
        }
        public static byte[] GetThumbnail(Image Img, int Width, int Height)
        {
            if (Width == -1)
                Width = Img.Width;
            if (Height == -1)
                Height = Img.Height;

            MemoryStream ms = new MemoryStream();
            Bitmap bmp = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
            Graphics grp = Graphics.FromImage(bmp);

            grp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            grp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            grp.DrawImage(Img, -1, -1, Width + 2, Height + 2);
            //grp.DrawImage(Img, 0, 0, Width, Height);

            bmp.Save(ms, ImageFormat.Jpeg);
            byte[] result = ms.ToArray();
            ms.Close();

            return result;
        }

        public static byte[] GetThumbnail(Image Img, int Max)
        {
            if (Img.Width > Img.Height)
                return GetThumbnail(Img, Max, Max * Img.Height / Img.Width);
            else
                return GetThumbnail(Img, Max * Img.Width / Img.Height, Max);
        }

        public static string GetParagraph(string Content, string ClassName, bool RemoveFormatting)
        {
            string content = Content.ToLower();
            string classname = ClassName.ToLower();
            int i = 0, j = 0;
            while (i != -1 && j != -1)
            {
                i = content.IndexOf("<p class=" + classname, j);
                if (i != -1)
                {
                    j = content.IndexOf("</p>", i);

                    int j2 = Content.IndexOf("<p", i + 1, j - i);
                    if (j2 != -1)
                        j = j2;

                    if (j != -1)
                    {
                        string paragraph = (RemoveFormatting ? StripHtml(Content.Substring(i, j - i)) : StripParagraph(Content.Substring(i, j - i)));
                        if (paragraph.Length != 0)
                            return paragraph;
                    }
                }
            }

            return string.Empty;
        }

        public static int GetIdFromRequestString(string RequestString, int DefaultID)
        {
            RequestString = System.Web.HttpContext.Current.Request.QueryString[RequestString];
            if (RequestString != null)
                try
                {
                    return int.Parse(RequestString);
                }
                catch { }

            return DefaultID;
        }

        public static string GetRequestString(string RequestString, string DefaultString)
        {
            RequestString = System.Web.HttpContext.Current.Request.QueryString[RequestString];
            if (RequestString != null && RequestString != string.Empty)
                return RequestString;
            return DefaultString;
        }

        public static DateTime GetDateFromRequestString(string RequestString, DateTime DefaultDate)
        {
            RequestString = System.Web.HttpContext.Current.Request.QueryString[RequestString];
            if (RequestString != null)
                try
                {
                    DateTime dt = DateTime.Parse(RequestString);
                    if (dt < DefaultDate)
                        DefaultDate = dt;
                }
                catch { }

            return DefaultDate.Date;
        }

    }
}